package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1;

import com.gzhryc.common.ImageTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.EncryptTools;
import com.gzhryc.dictionary.dao.db.CountryArea;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.servlet.upload.UploadFiles;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.ResourceAPIServer;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.config.dao.db.LogisticsCompany;
import com.gzhryc.shared_device.oem.code.config.services.LogisticsCompanyService;
import com.gzhryc.shared_device.oem.code.config.services.dto.LogisticsCompanySearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.*;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.device.BusinessTypeListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.device.BusinessTypeListResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

public class CommonController {

    static Logger log = Logger.getLogger(CommonController.class);

    @Route(value = "/agent/api/v1/common/user/find.do")
    public FindUserResponse deviceFuncList(HttpServletRequest request) {
        FindUserResponse apiResp = new FindUserResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        FindUserRequest apiReq = WebUtils.getJsonRequest(request, FindUserRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getPhone())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                if(user != null) {
                    AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),user.getId());

                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                    apiResp.getBody().setUserId(user.getId());
                    apiResp.getBody().setNickname(user.getNickname());
                    apiResp.getBody().setPhone(user.getPhone());
                    if(agentRelation != null) {
                    	apiResp.getBody().setRoleType(agentRelation.getRoleType());
                    	apiResp.getBody().setRoleTypeName(agentRelation.getRoleTypeName());
                    }
                    
                }
            }
        }
        return apiResp;
    }

    /**
     * 获取快递公司
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/common/logistics_company/list.data")
    public FindLogisticsCompanyResponse logisticsCompanyList(HttpServletRequest request) {
        FindLogisticsCompanyResponse apiResp = new FindLogisticsCompanyResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        FindLogisticsCompanyRequest apiReq = WebUtils.getJsonRequest(request, FindLogisticsCompanyRequest.class);
        if (apiReq != null) {
            LogisticsCompanySearch search = new LogisticsCompanySearch();
            search.setName(apiReq.getBody().getName());
            List<LogisticsCompany> logisticsCompanyList = LogisticsCompanyService.self().findBySearch(search,apiReq.getBody().getPageNo(),apiReq.getBody().getPageLimit());
            if(logisticsCompanyList != null && logisticsCompanyList.size() > 0){
                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                apiResp.getBody().setItems(new ArrayList<>());
                for(LogisticsCompany logisticsCompany : logisticsCompanyList){
                    FindLogisticsCompanyResponse.Item item = new FindLogisticsCompanyResponse.Item();
                    item.setId(logisticsCompany.getId());
                    item.setName(logisticsCompany.getName());
                    apiResp.getBody().getItems().add(item);
                }
            }
        }
        return apiResp;
    }

    /**
     * 业务类型,全局
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/common/business_type/select.data")
    public BusinessTypeListResponse selectBusinessTypeList(HttpServletRequest request) {
        BusinessTypeListResponse apiResp = new BusinessTypeListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        BusinessTypeListRequest apiReq = WebUtils.getJsonRequest(request, BusinessTypeListRequest.class);
        apiResp.getBody().setItems(new ArrayList<>());

        if (BaseConstants.getCDCZ()) {
        	boolean flag = true;
        	if(apiReq != null && apiReq.getBody().getRemoveBusinessTypes() != null && apiReq.getBody().getRemoveBusinessTypes().size() > 0) {
        		for(String temp : apiReq.getBody().getRemoveBusinessTypes()) {
        			if(temp.equals(EBusinessType.CDCZ.index())) {
        				flag = false;
        				break;
        			}
        		}
        	}
        	if(flag) {
	        	BusinessTypeListResponse.Item item = new BusinessTypeListResponse.Item();
	            item.setBusinessType(EBusinessType.CDCZ.index());
	            item.setBusinessTypeName(EBusinessType.CDCZ.note());
	            apiResp.getBody().getItems().add(item);
        	}
        }
        if (BaseConstants.getBXSCN()) {
        	boolean flag = true;
        	if(apiReq != null && apiReq.getBody().getRemoveBusinessTypes() != null && apiReq.getBody().getRemoveBusinessTypes().size() > 0) {
        		for(String temp : apiReq.getBody().getRemoveBusinessTypes()) {
        			if(temp.equals(EBusinessType.BXSCN.index())) {
        				flag = false;
        				break;
        			}
        		}
        	}
        	if(flag) {
	        	BusinessTypeListResponse.Item item = new BusinessTypeListResponse.Item();
	            item.setBusinessType(EBusinessType.BXSCN.index());
	            item.setBusinessTypeName(EBusinessType.BXSCN.note());
	            apiResp.getBody().getItems().add(item);
        	}
        	
        	flag = true;
        	if(apiReq != null && apiReq.getBody().getRemoveBusinessTypes() != null && apiReq.getBody().getRemoveBusinessTypes().size() > 0) {
        		for(String temp : apiReq.getBody().getRemoveBusinessTypes()) {
        			if(temp.equals(EBusinessType.BXSCN_SHOP.index())) {
        				flag = false;
        				break;
        			}
        		}
        	}
        	if(flag) {
        		BusinessTypeListResponse.Item item = new BusinessTypeListResponse.Item();
	            item.setBusinessType(EBusinessType.BXSCN_SHOP.index());
	            item.setBusinessTypeName(EBusinessType.BXSCN_SHOP.note());
	            apiResp.getBody().getItems().add(item);
        	}
        }
        if (BaseConstants.getCDB()) {
        	boolean flag = true;
        	if(apiReq != null && apiReq.getBody().getRemoveBusinessTypes() != null && apiReq.getBody().getRemoveBusinessTypes().size() > 0) {
        		for(String temp : apiReq.getBody().getRemoveBusinessTypes()) {
        			if(temp.equals(EBusinessType.CDB.index())) {
        				flag = false;
        				break;
        			}
        		}
        	}
        	if(flag) {
	        	BusinessTypeListResponse.Item item = new BusinessTypeListResponse.Item();
	            item.setBusinessType(EBusinessType.CDB.index());
	            item.setBusinessTypeName(EBusinessType.CDB.note());
	            apiResp.getBody().getItems().add(item);
        	}
        }
        if (BaseConstants.getPCL()) {
        	boolean flag = true;
        	if(apiReq != null && apiReq.getBody().getRemoveBusinessTypes() != null && apiReq.getBody().getRemoveBusinessTypes().size() > 0) {
        		for(String temp : apiReq.getBody().getRemoveBusinessTypes()) {
        			if(temp.equals(EBusinessType.PCL.index())) {
        				flag = false;
        				break;
        			}
        		}
        	}
        	if(flag) {
	        	BusinessTypeListResponse.Item item = new BusinessTypeListResponse.Item();
	            item.setBusinessType(EBusinessType.PCL.index());
	            item.setBusinessTypeName(EBusinessType.PCL.note());
	            apiResp.getBody().getItems().add(item);
        	}
        }
        if (apiResp.getBody().getItems().size() > 0) {
            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
        }
        return apiResp;
    }

    /**
     * 获取地区数据
     * @param request
     * @param response
     * @return
     */
    @Route("/agent/api/v1/common/china/area/select.data")
    public ChinaAreaJsonResponse select(HttpServletRequest request, HttpServletResponse response){
        ChinaAreaJsonResponse apiResp = new ChinaAreaJsonResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        List<CountryArea> data = CountryAreaUtils.getCountryAreaList();
        if(data != null && data.size() > 0){
            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setData(new HashMap<>());
            for(CountryArea province : data){
                Map<String,List<String>> item = new HashMap<>();
                if(province.getChildren() != null && province.getChildren().size() > 0){
                    for(CountryArea city : province.getChildren()){
                        List<String> cc = new ArrayList<>();
                        if(city.getChildren() != null && city.getChildren().size() > 0){
                            for(CountryArea cityArea : city.getChildren()) {
                                cc.add(cityArea.getName());
                            }
                        }
                        item.put(city.getName(),cc);
                    }
                }
                apiResp.getBody().getData().put(province.getName(),item);
            }
        }
        return apiResp;
    }

    @Route(value = {"/agent/api/v1/place/img/upload.do"})
    public ImageUploadResponse uploadPlaceImg(HttpServletRequest request, UploadFiles uploadFiles) {
        ImageUploadResponse result = new ImageUploadResponse(ClientAPICodeConstants.EXECUTE_ERROR, "上传失败，请稍后再试");
        FileItem fileItem = uploadFiles.getFirstFile();
        if (fileItem != null) {
            try {
                String extension = FilenameUtils.getExtension(fileItem.getName());
                if("webp".equals(extension)){
                    extension = "jpg";
                }
                
                //检查是否是本地资源
                if(WebConstants.isLocalRes()) {
                	String localDir = PropertyTools.get().getString("localDir","");
                	String filePath =  ResourceAPIServer.placePath + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
                	//保存到本地资源文件里
                	String path = PropertyTools.get().getString("localResPath") + localDir + filePath;
	                File file = new File(path);
	                fileItem.write(file);
	                
	                BufferedImage image = ImageIO.read(file);		//图片格式不正确读取或NULL
	                if(image != null) {
	                	//压缩
	                	BufferedImage thumbnailImg = ImageTools.thumbnailAndCropping(image,ResourceAPIServer.placeThumbWidth,ResourceAPIServer.placeThumbHeight);
	                	ImageIO.write(thumbnailImg, "jpg", file);
	                }
                	
	                result.setCode(ClientAPICodeConstants.SUCCESS, null);
                    String resDomain = PropertyTools.get().getString(WebConstants.CONF_RES_DOMAIN_KEY);
                    result.getBody().setPath(filePath);
                    result.getBody().setImgUrl(resDomain + filePath);
                }else {
                	//远端资源
	                String path = PropertyTools.get().getString("tempPath") + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
	                File file = new File(path);
	                fileItem.write(file); // 保存临时文件
	                
	                BufferedImage image = ImageIO.read(file);		//图片格式不正确读取或NULL
	                if(image != null) {
	                	//压缩
	                	BufferedImage thumbnailImg = ImageTools.thumbnailAndCropping(image,ResourceAPIServer.placeThumbWidth,ResourceAPIServer.placeThumbHeight);
	                	ImageIO.write(thumbnailImg, "jpg", file);
	                }
	
	                // 上传资源文件
	                path = ResourceAPIServer.self().uploadImg(ResourceAPIServer.placePath, file);
	                if (StringUtils.isNotBlank(path)) {
	                    result.setCode(ClientAPICodeConstants.SUCCESS, null);
	                    String resDomain = PropertyTools.get().getString(WebConstants.CONF_RES_DOMAIN_KEY);
	                    result.getBody().setPath(path);
	                    result.getBody().setImgUrl(resDomain + path);
	                }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            result.setMsg("获取图片信息失败");
        }
        return result;
    }

    @Route(value = {"/agent/api/v1/user/img/upload.do"})
    public ImageUploadResponse uploadUserImg(HttpServletRequest request, UploadFiles uploadFiles) {
        ImageUploadResponse result = new ImageUploadResponse(ClientAPICodeConstants.EXECUTE_ERROR, "上传失败，请稍后再试");
        FileItem fileItem = uploadFiles.getFirstFile();
        if (fileItem != null) {
            try {
                String extension = FilenameUtils.getExtension(fileItem.getName());
                
                if(WebConstants.isLocalRes()) {
                	String localDir = PropertyTools.get().getString("localDir","");
                	String filePath =  ResourceAPIServer.agentPath + "/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension;
                	//保存到本地资源文件里
                	String path = PropertyTools.get().getString("localResPath") + localDir + filePath;
	                File file = new File(path);
	                fileItem.write(file);
	                
	                result.setCode(ClientAPICodeConstants.SUCCESS, null);
                    String resDomain = PropertyTools.get().getString(WebConstants.CONF_RES_DOMAIN_KEY);
                    result.getBody().setPath(filePath);
                    result.getBody().setImgUrl(resDomain + filePath);
                }else {
                	//远端资源
	                String path = request.getServletContext().getRealPath("/temp/" + EncryptTools.md5(UUID.randomUUID() + fileItem.getName()) + "." + extension);
	                File file = new File(path);
	                file.getParentFile().mkdirs();
	                fileItem.write(file); // 保存临时文件
	
	                // 上传资源文件
	                path = ResourceAPIServer.self().uploadImg(ResourceAPIServer.agentPath, file);
	                if (StringUtils.isNotBlank(path)) {
	                    result.setCode(ClientAPICodeConstants.SUCCESS, null);
	                    String resDomain = PropertyTools.get().getString(WebConstants.CONF_RES_DOMAIN_KEY);
	                    result.getBody().setPath(path);
	                    result.getBody().setImgUrl(resDomain + path);
	                }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            result.setMsg("获取图片信息失败");
        }
        return result;
    }
}
